<template>
  <div class="ml-upload-images">
    <ml-upload-image
      v-for="(image,i) in images"
      :id.sync="image.id"
      :key="i"
      class="form-item-image"
      :url="image.src||''"
      @delete="eventDelete(i)"
    />
    <ml-upload-image v-if="images.length<5" :key="key" @success="eventSuccess">
      <slot />
    </ml-upload-image>
  </div>
</template>
<script>
import MlUploadImage from './single.vue'

const getKey = function() {
  return '' + (new Date().getTime())
}
export default {
  name: 'MlUploadImages',
  components: { MlUploadImage },
  props: {
    // eslint-disable-next-line vue/require-default-prop
    imagesParam: [Array, Boolean]
  },
  data() {
    return {
      key: getKey(),
      images: []
    }
  },
  created() {
    if (Array.isArray(this.imagesParam)) {
      this.images = [...[], ...this.imagesParam]
    }
  },
  methods: {
    /**
     * 单个图片上传成功
     * @param _
     */
    eventSuccess: function(_) {
      this.images = this.uniqueImages(_)
      this.key = getKey()
    },
    /**
     * 单个图片删除
     * @param index
     */
    eventDelete: function(index) {
      this.images.splice(index, 1)
    },
    /**
     * 图片去重
     * @param _
     * @returns {*[]}
     */
    uniqueImages: function(_) {
      const data = [...[], ...this.images]
      data.push(_)
      const images = []
      data.map(datum => {
        images.push(datum)
      })
      return images
    }
  }
}
</script>
<style scoped lang='scss'>
.ml-upload-images {
  display: flex;
  align-items: center;

  .ml-upload-image + .ml-upload-image {
    margin-left: 12px;
  }
}
</style>
